#include "material.h"
#include "unistate.h"

using namespace goatgfx;

Material::Material()
	: diffuse(1, 1, 1), specular(0, 0, 0)
{
	alpha = 1.0;
	shininess = 1.0;

	for(int i=0; i<MAX_MTL_TEXTURES; i++) {
		tex[i] = 0;
	}
}


void Material::setup(bool use_textures) const
{
	static bool done_init;
	static int st_diffuse_idx, st_specular_idx, st_shininess_idx, st_alpha_idx;
	static int st_tex_diffuse_idx, st_tex_specular_idx, st_tex_normal_idx;
	static int st_tex_idx[MAX_MTL_TEXTURES];

	if(!done_init) {
		st_diffuse_idx = add_unistate("st_mtl_diffuse", ST_FLOAT3);
		st_specular_idx = add_unistate("st_mtl_specular", ST_FLOAT3);
		st_shininess_idx = add_unistate("st_mtl_shininess", ST_FLOAT);
		st_alpha_idx = add_unistate("st_mtl_alpha", ST_FLOAT);
		st_tex_diffuse_idx = add_unistate("st_tex_diffuse", ST_INT);
		st_tex_specular_idx = add_unistate("st_tex_specular", ST_INT);
		st_tex_normal_idx = add_unistate("st_tex_normal", ST_INT);

		for(int i=0; i<MAX_MTL_TEXTURES; i++) {
			char name[32];
			sprintf(name, "st_tex%d", i);
			st_tex_idx[i] = add_unistate(name, ST_INT);
		}
		done_init = true;
	}

	set_unistate(st_diffuse_idx, diffuse);
	set_unistate(st_specular_idx, specular);
	set_unistate(st_shininess_idx, shininess);
	set_unistate(st_alpha_idx, alpha);

	if(!use_textures) {
		return;	// we're done
	}

	const int tex_named_idx[] = {
		st_tex_diffuse_idx, st_tex_specular_idx, st_tex_normal_idx, -1
	};

	int tex_unit = 0;
	for(int i=0; i<MAX_MTL_TEXTURES; i++) {
		if(tex[i]) {
			tex[i]->bind(tex_unit);

			if(tex_named_idx[i]) {
				set_unistate(tex_named_idx[i], tex_unit);
			}
			set_unistate(st_tex_idx[i], tex_unit);
			tex_unit++;
		}
	}
}
